<script setup lang="jsx">
import { reactive, ref } from 'vue';
import { parseTime } from '@/utils';
import {
  basicmodelareaadd,
  basicmodelareadelete,
  basicmodelarealistData,
  basicmodelareaupdate
} from '@/service/api/modules/erp';

import Modal from '@/components/common/modal.vue';

import Search from './modules/search.vue';
const searchParams = ref({
  areaId: ''
});

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

const columns = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 100,
    align: 'center',
    checked: true
  },
  {
    key: 'areaId',
    dataIndex: 'areaId',
    title: '作业区域代码',
    width: 260,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'description',
    dataIndex: 'description',
    title: '描述',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'siteId',
    dataIndex: 'siteId',
    title: '工厂代码',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'lmUser',
    dataIndex: 'lmUser',
    title: '最后修改用户',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'lmTime',
    dataIndex: 'lmTime',
    title: '最后修改时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.lmTime == null) {
        return null;
      }
      return parseTime(record.lmTime);
    }
  }
]);
const formState = ref({});
const detailsVisibleQrcode = ref(false);

const tableData = ref([]);
const loading = ref(false);
const defaultExpandedRowKeys = ref([]);

function getData() {
  loading.value = true;
  basicmodelarealistData({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...searchParams.value
  })
    .then(({ data, error }) => {
      if (!error) {
        data.list.forEach((item, index) => {
          item.index = index + 1;
        });
        tableData.value = data.list;
        pagination.total = data.total;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
const selectedRowKeys = ref([]);
const formTit = ref('');
function tableSelectChange(val) {
  selectedRowKeys.value = val;
}
function manualSyncing() {
  formState.value = {};
  detailsVisibleQrcode.value = true;
  formTit.value = '工厂区域新增';
}

function boundUpdata(val) {
  if (val == '工厂区域新增') {
    basicmodelareaadd(formState.value).then(({ data, error }) => {
      if (!error) {
        window.$message?.success('新增成功');
        detailsVisibleQrcode.value = false;
        getData();
      }
    });
  } else {
    basicmodelareaupdate(formState.value).then(({ data, error }) => {
      if (!error) {
        window.$message?.success('修改成功');
        detailsVisibleQrcode.value = false;
        getData();
      }
    });
  }
}

function updateSyncing() {
  if (selectedRowKeys.value.length !== 1) {
    return window.$message?.error('请选择一条数据');
  }
  const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.areaUuid));
  formTit.value = '工厂区域修改';
  formState.value = selectData[0];
  console.log('formState.value', formState.value);

  detailsVisibleQrcode.value = true;
}
function deleteSyncing() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请选择数据');
  }
  window.$modal.confirm({
    title: '提醒',
    content: '确认删除所选数据吗？',
    onOk: () => {
      const deleteData = selectedRowKeys.value;
      basicmodelareadelete(deleteData).then(({ error, data }) => {
        if (!error) {
          window.$message?.success('删除成功');

          getData();
        }
      });
    },
    onCancel: () => {}
  });
}
getData();

function search() {
  pagination.current = 1;
  getData();
}

const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      background: record.areaUuid === currentRowId.value ? '#BAEAFA' : ''
    },
    class: record.areaUuid === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.areaUuid;
    }
  };
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="search()" @search="search()" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="manualSyncing">
          <span class="ml-3px">新增</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="updateSyncing">
          <span class="ml-3px">修改</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteSyncing">
          <span class="ml-3px">删除</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <STable
        :columns="columns"
        :data-source="tableData"
        size="small"
        bordered
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
        :default-expanded-row-keys="defaultExpandedRowKeys"
        row-key="areaUuid"
        :default-expand-all-rows="true"
        :scroll="{ x: 'auto', y: 'auto' }"
        :pagination="pagination"
        class="h-full"
        :custom-row="customRow"
        :row-height="23"
      />
      <Modal
        v-model:visible="detailsVisibleQrcode"
        :destroy-on-close="true"
        :centered="true"
        :title="formTit"
        width="950px"
        height="350px"
      >
        <div class="event-form">
          <AForm :model="formState" name="basic" :label-col="{ span: 6 }" autocomplete="off">
            <ARow>
              <ACol :span="24">
                <AFormItem
                  label="作业区域代码"
                  name="areaId"
                  :rules="[{ required: true, message: '请选择作业区域代码!' }]"
                >
                  <AInput v-model:value="formState.areaId" allow-clear />
                </AFormItem>
              </ACol>
              <ACol :span="24">
                <AFormItem label="描述" name="description">
                  <AInput v-model:value="formState.description" allow-clear />
                </AFormItem>
              </ACol>
            </ARow>
          </AForm>
        </div>

        <template #footer>
          <div class="modal-footer">
            <AButton @click="detailsVisibleQrcode = false">关闭</AButton>
            <AButton type="primary" @click="boundUpdata(formTit)">保存</AButton>
          </div>
        </template>
      </Modal>
    </ACard>
  </div>
</template>

<style></style>
